package cn.redragon.soa.common.web;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JsoupUtil {

    private static final Whitelist whitelist = initWhiteList();
    private static final Document.OutputSettings outputSettings = new Document.OutputSettings()
        .prettyPrint(false);

    public static String clean(String content) {
  /*      if (isNotBlank(content)) {
            return Jsoup.clean(decode(content), "", whitelist, outputSettings);
        }*/
        return content;
    }

    private static Whitelist initWhiteList() {
        Whitelist whitelist = Whitelist.relaxed();
        whitelist.addAttributes("img", "data-componenttype", "data-linkdata");
        whitelist.addAttributes("a", "data-linkdata");
        whitelist.addAttributes("button", "data-linkdata");
        whitelist.addAttributes("span", "class", "contenteditable");
        whitelist.addAttributes("video", "poster", "controls", "width", "height");
        whitelist.addAttributes("source", "src", "type", "data-mce-src");

        Stream.of("h1", "h2", "h3", "h4", "h5", "h6", "p", "br", "hr", "acronym", "abbr",
                  "address", "b", "bdi", "bdo", "big", "blockquote", "center", "cite", "code", "del", "dfn", "em",
                  "font", "i", "ins", "kbd", "mark", "meter", "pre", "progress", "q", "rp", "rt", "ruby", "s",
                  "samp", "small", "strike", "strong", "sub", "sup", "time", "tt", "u", "wbr", "form", "input",
                  "textarea", "button", "select", "optgroup", "option", "label", "fieldset", "legend", "datalist",
                  "keygen", "output", "img", "area", "canvas", "figcaption", "figure", "audio", "track",
                  "a", "main", "nav", "ul", "ol", "li", "dir", "dl", "dt", "dd", "menu", "command",
                  "table", "caption", "th", "tr", "td", "thead", "tbody", "tfoot", "col", "colgroup", "div",
                  "header", "footer", "section", "article", "aside", "details", "dialog", "summary", "source", "video", "span")
            .forEach(tag -> whitelist.addAttributes(tag, "style"));

        return whitelist;
    }

    private static String decode(String data) {
        try {
            data = data.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            data = data.replaceAll("\\+", "%2B");
            data = URLDecoder.decode(data, StandardCharsets.UTF_8);
        } catch (Exception e) {
            return "";
        }
        return data;
    }

}
